package com.example.videoplayer;

import android.util.Log;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

import org.json.JSONException;
import org.json.JSONObject;

// WebSocket管理器类
public class WebSocketManager {
    private static final long PING_INTERVAL = 2000; // 心跳间隔时间，单位毫秒
    private static final long PONG_TIMEOUT = 4000; // pong响应超时时间，单位毫秒
    private WebSocketMessageListener listener;
    private WebSocket webSocket;
    private final OkHttpClient client = new OkHttpClient();
    CountDownLatch pongLatch = new CountDownLatch(1); // 创建一个CountDownLatch来等待pong响应
    public void start(String url, WebSocketMessageListener listener) {
        this.listener = listener;
        Request request = new Request.Builder().url(url).build();
        webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, okhttp3.Response response) {
                // WebSocket连接打开时的处理
                startHeartbeat(); // 连接成功后启动心跳机制
//                Log.d("消息","连上");
            }
            @Override
            public void onMessage(WebSocket webSocket, String text) {
                // 收到消息时的处理
                try {
                    JSONObject jsonObject = new JSONObject(text);
                    // 解析 JSON 对象
                    int type = jsonObject.getInt("type");
                    String value = jsonObject.getString("value");
                    Log.d("asdsd2",value);
                    pongLatch.countDown();
//                    if(type!= 1){
                        listener.onMessage(text);
//                    }
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                // 处理WebSocket连接异常
                Log.d("asdsdss3",t.getMessage());
            }
            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                Log.d("asdsdss2",reason);
                // WebSocket连接关闭时的处理
            }
        });
    }

    public void sendMessage(String message) {
        if (webSocket != null) {
            webSocket.send(message);
        }
    }
    private void startHeartbeat() {
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(PING_INTERVAL);
                    if (webSocket != null) {
//                        Log.d("消息2","心跳");
                        JSONObject heartbeat = new JSONObject();
                        heartbeat.put("type", 1); // 假设 "1" 表示心跳类型
                        heartbeat.put("value", "PING");

                        webSocket.send(heartbeat.toString()); // 发送ping消息
//                        Log.d("消息3",heartbeat.toString());
                        System.out.println("Sent ping");

                        // 等待pong响应，或者超时
                        if (!pongLatch.await(PONG_TIMEOUT, TimeUnit.MILLISECONDS)) {
                            Log.d("asdsd4","异常");
                            System.out.println("Pong timeout, closing WebSocket connection");
                            webSocket.close(1000, "Pong timeout");
                            break; // 退出心跳线程
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
    public void close() {
        if (webSocket != null) {
            webSocket.close(1000, "Normal closure");
        }
    }
}
